{% extends 'base.html' %}
{% load static %}

{% block title %}发现活动 - 本地有约{% endblock %}

{% block extra_css %}
<style>
    .activities-container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 2rem 1rem;
    }
    
    .section-title {
        margin-bottom: 2rem;
        font-weight: 700;
        position: relative;
    }
    
    .section-title::after {
        content: '';
        position: absolute;
        bottom: -8px;
        left: 0;
        width: 60px;
        height: 4px;
        background: var(--gradient-primary);
        border-radius: 2px;
    }
    
    .filter-section {
        background: white;
        border-radius: 1rem;
        padding: 1.5rem;
        box-shadow: var(--shadow-md);
        margin-bottom: 2rem;
    }
    
    .create-activity-btn {
        background: var(--gradient-primary);
        color: white;
        border: none;
        padding: 0.75rem 1.5rem;
        border-radius: 0.5rem;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 0 4px 14px rgba(111, 66, 193, 0.3);
    }
    
    .create-activity-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(111, 66, 193, 0.4);
    }
    
    .activity-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 1.5rem;
    }
    
    .activity-card {
        background: white;
        border-radius: 1rem;
        overflow: hidden;
        box-shadow: var(--shadow-md);
        transition: all 0.3s ease;
        display: flex;
        flex-direction: column;
    }
    
    .activity-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    }
    
    .activity-image {
        height: 180px;
        overflow: hidden;
    }
    
    .activity-image img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.5s ease;
    }
    
    .activity-card:hover .activity-image img {
        transform: scale(1.05);
    }
    
    .activity-content {
        padding: 1.5rem;
        flex: 1;
        display: flex;
        flex-direction: column;
    }
    
    .activity-title {
        font-size: 1.25rem;
        font-weight: 600;
        margin-bottom: 0.75rem;
        color: var(--text-primary);
        line-height: 1.4;
    }
    
    .activity-meta {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 1rem;
        color: var(--gray-text);
        font-size: 0.875rem;
    }
    
    .activity-meta i {
        color: var(--primary-color);
        margin-right: 0.25rem;
    }
    
    .activity-footer {
        margin-top: auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 1rem;
        border-top: 1px solid var(--border-color);
    }
    
    .activity-type-badge {
        background: var(--gradient-primary-light);
        color: var(--primary-color);
        font-size: 0.75rem;
        padding: 0.25rem 0.75rem;
        border-radius: 50px;
        font-weight: 600;
    }
    
    .activity-price {
        font-weight: 700;
        color: var(--success-color);
    }
    
    .activity-price.paid {
        color: var(--warning-color);
    }
    
    .empty-state {
        text-align: center;
        padding: 4rem 2rem;
        background: var(--light-bg);
        border-radius: 1rem;
    }
    
    .empty-state i {
        font-size: 4rem;
        color: var(--primary-color-light);
        margin-bottom: 1rem;
    }
    
    .loading-state {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 3rem 0;
    }
</style>
{% endblock %}

{% block content %}
<div class="activities-container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="section-title">发现活动</h1>
        {% if user.is_authenticated %}
        <a href="{% url 'activities:create' %}" class="create-activity-btn">
            <i class="fas fa-plus-circle"></i> 创建活动
        </a>
        {% else %}
        <a href="{% url 'users:login' %}" class="create-activity-btn">
            <i class="fas fa-plus-circle"></i> 创建活动
        </a>
        {% endif %}
    </div>
    
    <!-- 筛选部分 -->
    <div class="filter-section">
        <div class="filter-tabs">
            <div class="search-filter">
                <input type="text" id="searchInput" placeholder="搜索活动、地点或关键词" class="search-input">
            </div>
            
            <div class="filter-dropdowns">
                <div class="filter-dropdown">
                    <select id="sortSelect">
                        <option value="newest">
                            <i class="fas fa-calendar-alt"></i> 最新发布
                        </option>
                        <option value="popularity">
                            <i class="fas fa-fire"></i> 最热门
                        </option>
                        <option value="view_count">
                            <i class="fas fa-eye"></i> 最多浏览
                        </option>
                    </select>
                </div>
                
                <div class="filter-dropdown">
                    <select id="feeSelect">
                        <option value="all">
                            <i class="fas fa-wallet"></i> 全部费用
                        </option>
                        <option value="free">
                            <i class="fas fa-ticket-alt"></i> 免费活动
                        </option>
                        <option value="paid">
                            <i class="fas fa-tag"></i> 付费活动
                        </option>
                    </select>
                </div>
            </div>
            
            <div class="filter-status-buttons">
                <button class="filter-tab active" data-status="all">全部</button>
                <button class="filter-tab" data-status="upcoming">即将开始</button>
                <button class="filter-tab" data-status="ongoing">进行中</button>
            </div>
        </div>
        
        <div class="filter-categories mt-3">
            <h5 class="mb-2">活动类型</h5>
            <div class="category-tags">
                <label class="category-tag active">
                    <input type="radio" name="activityType" value="all" checked> 全部类型
                </label>
                {% for type in activity_types %}
                <label class="category-tag">
                    <input type="radio" name="activityType" value="{{ type.id }}"> {{ type.name }}
                </label>
                {% endfor %}
            </div>
        </div>
    </div>
    
    <!-- 活动列表 -->
    <div id="activitiesList" class="activity-grid">
        <div class="loading-state">
            <div class="loading-spinner"></div>
        </div>
    </div>
    
    <!-- 加载更多 -->
    <div class="text-center mt-4">
        <button id="loadMoreBtn" class="btn btn-outline-primary" style="display: none;">
            加载更多
        </button>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 活动列表页面交互
    document.addEventListener('DOMContentLoaded', function() {
        let currentPage = 1;
        let isLoading = false;
        
        // 初始加载活动
        loadActivities();
        
        // 筛选条件变更时重新加载
        document.querySelectorAll('select, input[name="activityType"], .filter-tab').forEach(element => {
            element.addEventListener('change', () => {
                currentPage = 1;
                loadActivities();
            });
        });
        
        // 搜索框输入事件
        const searchInput = document.getElementById('searchInput');
        searchInput.addEventListener('input', debounce(() => {
            currentPage = 1;
            loadActivities();
        }, 500));
        
        // 加载更多按钮
        document.getElementById('loadMoreBtn').addEventListener('click', () => {
            if (!isLoading) {
                loadMoreActivities();
            }
        });
        
        // 更新状态按钮样式
        document.querySelectorAll('.filter-tab').forEach(button => {
            button.addEventListener('click', function() {
                updateStatusButton(this);
            });
        });
    });
    
    // 更新状态按钮样式
    function updateStatusButton(clickedButton) {
        // 移除所有按钮的active类
        document.querySelectorAll('.filter-tab').forEach(btn => {
            btn.classList.remove('active');
        });
        // 为当前按钮添加active类
        clickedButton.classList.add('active');
    }
    
    // 加载活动列表
    function loadActivities() {
        const activitiesList = document.getElementById('activitiesList');
        activitiesList.innerHTML = '<div class="loading-state"><div class="loading-spinner"></div></div>';
        
        fetchActivities(1, true);
    }
    
    // 加载更多活动
    function loadMoreActivities() {
        const loadMoreBtn = document.getElementById('loadMoreBtn');
        loadMoreBtn.innerHTML = '<div class="loading-spinner"></div>';
        
        fetchActivities(currentPage + 1, false);
    }
    
    // 获取活动数据
    function fetchActivities(page, replace = true) {
        const sortSelect = document.getElementById('sortSelect');
        const feeSelect = document.getElementById('feeSelect');
        const searchInput = document.getElementById('searchInput');
        const activityType = document.querySelector('input[name="activityType"]:checked').value;
        const statusFilter = document.querySelector('.filter-tab.active').dataset.status;
        
        const params = new URLSearchParams();
        params.append('page', page);
        params.append('sort', sortSelect.value);
        params.append('fee', feeSelect.value);
        params.append('type', activityType === 'all' ? '' : activityType);
        params.append('status', statusFilter);
        params.append('search', searchInput.value);
        
        isLoading = true;
        
        fetch(`{% url 'activities:api_list' %}?${params.toString()}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    renderActivities(data.data.results, replace);
                    
                    currentPage = page;
                    
                    // 更新加载更多按钮状态
                    const loadMoreBtn = document.getElementById('loadMoreBtn');
                    if (page < data.data.pagination.total_pages) {
                        loadMoreBtn.style.display = 'block';
                        loadMoreBtn.innerHTML = '加载更多';
                    } else {
                        loadMoreBtn.style.display = 'none';
                    }
                } else {
                    showError(data.message || '加载活动失败');
                }
            })
            .catch(error => {
                console.error('Error fetching activities:', error);
                showError('网络错误，请稍后重试');
            })
            .finally(() => {
                isLoading = false;
            });
    }
    
    // 渲染活动列表
    function renderActivities(activities, replace = true) {
        const activitiesList = document.getElementById('activitiesList');
        
        if (activities.length === 0) {
            activitiesList.innerHTML = `
                <div class="empty-state">
                    <i class="far fa-calendar-alt"></i>
                    <h3>暂无活动</h3>
                    <p>当前筛选条件下暂无活动，试试其他筛选条件或创建新活动吧！</p>
                    {% if user.is_authenticated %}
                    <a href="{% url 'activities:create' %}" class="btn btn-primary mt-3">创建活动</a>
                    {% else %}
                    <a href="{% url 'users:login' %}" class="btn btn-primary mt-3">登录后创建活动</a>
                    {% endif %}
                </div>
            `;
            return;
        }
        
        let html = '';
        
        activities.forEach(activity => {
            const isFree = activity.is_free;
            html += `
                <div class="activity-card">
                    <div class="activity-image">
                        <img src="${activity.cover_image || '/static/img/default-activity.png'}" alt="${activity.title}">
                    </div>
                    <div class="activity-content">
                        <h3 class="activity-title">${activity.title}</h3>
                        <div class="activity-meta">
                            <span><i class="far fa-clock"></i> ${formatDate(activity.start_time)}</span>
                            <span><i class="fas fa-map-marker-alt"></i> ${activity.location_name}</span>
                        </div>
                        <p class="text-muted text-sm mb-3 line-clamp-2">${activity.description}</p>
                        <div class="activity-footer">
                            <span class="activity-type-badge">${activity.activity_type.name || '其他'}</span>
                            <span class="activity-price ${isFree ? '' : 'paid'}">${isFree ? '免费' : '¥' + activity.fee}</span>
                        </div>
                    </div>
                    <a href="/activities/detail/${activity.id}" class="stretched-link"></a>
                </div>
            `;
        });
        
        if (replace) {
            activitiesList.innerHTML = html;
        } else {
            activitiesList.innerHTML += html;
        }
    }
    
    // 显示错误信息
    function showError(message) {
        const activitiesList = document.getElementById('activitiesList');
        activitiesList.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-exclamation-circle"></i>
                <h3>出错了</h3>
                <p>${message}</p>
                <button onclick="loadActivities()" class="btn btn-primary mt-3">重试</button>
            </div>
        `;
    }
    
    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {month: '2-digit', day: '2-digit'});
    }
    
    // 防抖函数
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
</script>
{% endblock %}